import 'dart:async';

import 'package:camera/camera.dart';
import 'package:get/get.dart';
import 'package:squat_easy/se_db/se_db_database.dart';
import 'package:squat_easy/se_db/se_db_entity.dart';
import 'package:squat_easy/se_main/se_main_logic.dart';
import 'package:squat_easy/se_route.dart';
import 'package:squat_easy/se_service/se_user_service.dart';
import 'package:squat_easy/se_ui/se_dialogs.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

class SeVideoRecordLogic extends GetxController {
  List<CameraDescription> cameras = [];

  CameraController? cameraController;

  Timer? timer;

  String get userId => SeUserService.instance.userId;

  var duration = 0.obs;
  var count = 0.obs;
  var isRecording = false.obs;

  @override
  void onReady() async {
    super.onReady();

    cameras = await availableCameras();

    cameraController = CameraController(cameras[0], ResolutionPreset.veryHigh);
    cameraController?.initialize().then((_) {
      update();
    }).catchError((e) {});

    showStartDialog();
  }

  void showStartDialog() {
    SeDialogs.oneButton(
      title: "Starts counting every time you tap the screen",
      confirmTitle: 'OK',
      onConfirm: () {
        startTimer();

        ///开始录制视频
        cameraController?.startVideoRecording();
      },
    );
  }

  void incrementCounter() => count.value++;

  void startTimer() {
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      duration.value++;
    });

    isRecording.value = true;
  }

  void stopTimer() {
    timer?.cancel();
    timer = null;
    isRecording.value = false;
  }

  @override
  void onClose() {
    super.onClose();
    cameraController?.dispose();
    stopTimer();
  }

  void onSave() async {
    SeDialogs.twoButton(
      title: "Confirm that the recorded video was successful and saved?",
      cancelTitle: 'Keep recording',
      confirmTitle: 'Save video',
      onConfirm: () async {
        if (cameraController == null) return;

        XFile file = await cameraController!.stopVideoRecording();
        await saveToDb(file);
        saveSuccess();
      },
    );
  }

  Future saveToDb(XFile file) async {
    try {
      final database = await $FloorSeAppDatabase.databaseBuilder(SeDbConstant.databaseName).build();

      final dao = database.videoDao;

      Video video = Video(
        userId: userId,
        num: count.value,
        duration: duration.value,
        fileName: file.name,
        filePath: file.path,
      );

      await dao.insertVideo(video);
    } catch (e) {}
  }

  void saveSuccess() async {
    SeDialogs.twoButton(
      title: "Saved successfully, you can go to the logging area to view it.",
      cancelTitle: 'Return to',
      confirmTitle: 'leave',
      onCancel: () => CommonOperate.nextFrameRefresh(SeRoute.close),
      onConfirm: () {
        Get.find<SeMainLogic>().changeTabIndex(2);
        CommonOperate.nextFrameRefresh(SeRoute.close);
      },
    );
  }
}
